import router from "./router";
import store from "./store";


router.beforeEach(async (to, from, next) => {
    let token = store.getters.token
    let userInfo = store.getters.userInfo

    if (token) {
        if (to.path == '/login') {
            next(from.path)
        } else {
           if(to.path == "/"){
               next()
           }else{
               if(!userInfo){
                    let res = await store.dispatch('user/userInfo')
                    let menus = [];
                    res.menus.forEach((item)=>{
                        item.children.map((item)=>{
                            menus.push(item.name)
                        })
                    })
                    // console.log(menus);
                    const routers = await store.dispatch('permission/filterRoutes', menus)
                    routers.forEach(item=>{
                        router.addRoute(item)
                    })
                    next(to.path)
               }else{
                   next();
               }
           }
        }
    } else {
        if (to.path == '/login') {
            next()
        } else {
            next('/login')
        }
    }
})


 // if (to.path == '/') {
            //     if (!userInfo) {
                    // store.dispatch('user/userInfo').then(res => {
                    //     next()
                    // }).catch(error => {
                    //     next('/login')
                    // })
            //     } else {
            //         if (to.path == '/layout' && userInfo.menus == []) {
            //             store.dispatch("user/userInfo").then((res) => {
            //                 console.log(res);
            //                 let menus = res.menus.map((item) => {
            //                     return item.name;
            //                 });
            //                 store
            //                     .dispatch("permission/filterRoutes", menus)
            //                     .then((routers) => {
            //                         routers.forEach((item) => {
            //                             router.addRoute(item);
            //                         });
            //                         console.log(this.$router.getRoutes());
            //                     });
            //                     next();
            //             }).catch(error=>{
            //                 next(from.path)
            //             })
                        
            //         }
            //     }
            // } else {
            //     next();
            // }